package cn.itsource.hrm.exception;

import cn.itsource.hrm.util.AjaxResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常捕获器
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

/*    @ExceptionHandler(AccessDeniedException.class)
    public AjaxResult getAccessDeniedException(GlobalException e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage("没有权限！！");
    }*/

    @ExceptionHandler(GlobalException.class)
    public AjaxResult getGlobalException(GlobalException e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public AjaxResult getException(Exception e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage("系统故障，我们正在殴打程序员，请稍后。。。。");
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult getMethodArgumentNotValidException(MethodArgumentNotValidException e){
        //((FieldError)((java.util.LinkedList)((BeanPropertyBindingResult)e.bindingResult).errors).get(0)).defaultMessage
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        StringBuffer sb = new StringBuffer();
        errors.forEach(error->{
            sb.append(error.getDefaultMessage()).append(";");
        });
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage(sb.toString());
    }
}
